package com.itheima.contrlloer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.Student;
import com.itheima.service.StudentService;
import com.itheima.service.impl.StudentServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Map;
import java.util.List;

@WebServlet("/studentServlet")
public class StudentServlet extends HttpServlet {
    StudentService service = new StudentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取到具体什么请求的方法
        String method = req.getParameter("method");
        switch (method){
            case "addStudent":
                addStudent(req,resp);
                break;
        }
    }

    //添加
    private void addStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //调用实现层添加方法
        StudentService service = new StudentServiceImpl();
        //获取数据
        Map<String, String[]> map = req.getParameterMap();
        //传输数据
        service.addStudent((Student) map);

        //响应
        resp.getWriter().write("true");

        //转换成json
        String map1 = new ObjectMapper().writeValueAsString("map");

    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) {
        List<Student> students = service.selectAll();
        for (Student student : students) {
            System.out.println(student);
        }
    }
    /*
       修改数据功能
    */
    private void updateStudent(HttpServletRequest req, HttpServletResponse resp) {
        //获取请求参数
        Map<String, String[]> map = req.getParameterMap();
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");

        //封装Student对象
        Student student = new Student();


        try {
            BeanUtils.populate(student,map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //调用业务层的修改方法
        service.updateStudent(student);

        //重定向到分页查询功能
        try {
            resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
